<template>
  <div class="analyse" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other_half_hour" @isFold="isShowFold" :query="query" :isTimePeriod = "true"></date-time>
            <el-button type="primary" class="primary_btn fr find" v-on:click.stop="search">{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="accs">
                  <span class="access">{{$t('report.imAccessId')}}：</span>
                  <el-select size="mini" v-model.trim="selectedAccessIdList" multiple filterable :placeholder="$t('report.searchByName')">
                    <el-option
                      v-for="item in accessIdOptions"
                      :label="item.label"
                      :value="item.value"
                      :key="item.value">
                    </el-option>
                  </el-select>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="title"></affix>
    </div>
    <div>
      <el-row class="ichars" :id="id">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd && !isEcommerce"
            @click.stop="exportXls"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            v-if="!isEcommerce"
            @click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
          <el-select @change="changeLookData" size="mini" class="fr" style="width:120px" v-model="data_type">
            <el-option value="hasData" :label="$t('report.lookHasData')"></el-option>
            <el-option value="allData" :label="$t('report.lookHasAllData')"></el-option>
          </el-select>
        </div>
        <report-table ref="reportTableRef" :sum="totalData" :config="headOptions.Config"></report-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import unfold from '../../../ui-modules/unfold/index.vue'
  import affix from '../../../ui-modules/affix/Affix.vue'
  import dateTime from '../base/datetime.vue'
  import reportTable from '../base/optimizationTable.vue'
  import headerOption from '../base/headerOption.vue'
  import { deepClone, initFinishName } from '@/utils/m7Utils.js'
  import { exportReportPdfNew, headOptionsToXlsxHeaders, checkTime, searchTime, colorConfigArr } from '@/utils/reportUtils.js'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  import {sortBy} from 'lodash'

  export default {
    name: 'im_report_business_analyse',
    data () {
      return {
        highchartsOptions: {}, // 图
        tableData: [], // table
        totalData: [], // 合计
        data_type: 'hasData', // 查看数据类型
        finishOptions: [], // 结束类型
        isEcommerce: this.$store.getters.isEcommerce ? true : false,
        selectedAccessIdList: [], // 接入号绑定值
        isFold: false, // 展开收起查询条件开关
        accessIdOptions: [], // 渲染接入号数据
        id: 'im_report_business_analyse',
        title: this.$t('report.imReportBusinessAnalyse'),
        loading: false,
        query: {}, // 日期插件值
        serverData: [], // 表格数据
        headOptions: { Config: [], data: [] }, // 表头数据
        dialogVisible: false, // 导出pdf弹窗开关
        highchartsDefaultOptions: { // charts配置数据
          chart: { type: 'column', animation: false },
          colors: colorConfigArr,
          xAxis: {
            categories: [],
            title: {
              enabled: true,
              text: '',
              style: { fontWeight: 'normal' }
            }
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: { text: this.$t('report.imReportBusinessAnalyse') },
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          tooltip: {
            pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
            shared: true
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      reportTable,
      headerOption
    },
    methods: {
      // 切换数据查看方式
      changeLookData () {
        this.search()
      },
      handleFetchData (type) {
        let datas = deepClone(this.serverData) || []
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.serverData || this.serverData.length === 0) {
          this.highchartsOptions = options
          this.totalData = [{consultType: this.$t('report.total')}]
          this.tableData = []
          this.$refs.reportTableRef.reloadTableData([])
          return false
        }
        let seriesArray = []
        let headerConfig = this.headOptions.Config || []
        let categoriesArray = [] // highcharts 数据
        let chartTotal = [] // chart 合计
        let tableTotal = { consultType: this.$t('report.total') } // table 合计
        datas.forEach((item, index) => {
          item.consultType = this.finishOptions[item.consultType] || this.$t('report.imReportBusinessAnalyseDeletedType')
          categoriesArray.push(item.consultType)
          item.consultTotal = (item.pc || 0) + (item.sdk || 0) + (item.weixin || 0) + (item.wxmini || 0) + (item.wap || 0) + (item.weibo || 0) + (item.wxwork || 0) + (item.ocpc || 0) + (item.dy || 0) + (item.wxkf || 0)
          headerConfig.forEach(headerItem => {
            if (!isNaN(item[headerItem.name]) && headerItem.name !== 'consultType') {
              if ((headerItem.name in tableTotal) === false) {
                tableTotal[headerItem.name] = 0
              }
              tableTotal[headerItem.name] += item[headerItem.name]
            }
            if (headerItem.show && headerItem.name !== 'consultType' && headerItem.name !== 'consultTotal') {
              if (index < 1) { // 新取出
                let serie = { name: headerItem.displayname, data: [], valueName: headerItem.name }
                seriesArray.push(serie)
              }
            }
          })
          let t = 0
          seriesArray.forEach(seriesItem => {
            seriesItem.data.push(item[seriesItem.valueName])
            t += item[seriesItem.valueName]
          })
          chartTotal.push(t)
        })
        datas = sortBy(datas, (item) => {
          return -item.consultTotal
        })
        // 添加合计列
        seriesArray.push({name: this.$t('report.total2'), data: chartTotal, valueName: 'consultTotal'})
        options.xAxis.categories = categoriesArray
        options.series = seriesArray
        this.highchartsOptions = options
        this.$refs.reportTableRef.reloadTableData(datas)
        this.tableData = datas
        this.totalData = [tableTotal]
      },
      // getHighchartsOptions () {
      //   let options = deepClone(this.highchartsDefaultOptions)
      //   if (!this.serverData || this.serverData.length === 0) {
      //     return options
      //   }
      //
      //   let headerConfig = this.headOptions.Config || []
      //   let datas = this.serverData
      //   let categoriesArray = []
      //   let seriesArray = []
      //   let total = []
      //
      //   headerConfig.forEach(item => {
      //     if (!item.show) {
      //       return
      //     }
      //     if (item.name === 'consultType' || item.name === 'consultTotal') {
      //       return
      //     }
      //     let serie = { name: item.displayname, data: [], valueName: item.name }
      //     seriesArray.push(serie)
      //   })
      //   datas.forEach(item => {
      //     categoriesArray.push(this.finishOptions[item.consultType] || this.$t('report.imReportBusinessAnalyseDeletedType'))
      //     let t = 0
      //     seriesArray.forEach(item2 => {
      //       item2.data.push(item[item2.valueName])
      //       t += item[item2.valueName]
      //     })
      //     total.push(t)
      //   })
      //   // 添加合计列
      //   seriesArray.push({name: this.$t('report.total2'), data: total, valueName: 'consultTotal'})
      //
      //   options.xAxis.categories = categoriesArray
      //   options.series = seriesArray
      //
      //   return options
      // },
      // // 表格合计
      // getTotalData (serverData, headOptions) {
      //   if (!serverData || serverData.length === 0) {
      //     return [{consultType: this.$t('report.total')}]
      //   }
      //   let headerConfig = headOptions.Config || []
      //   let datas = serverData
      //   let total = { consultType: this.$t('report.total') }
      //
      //   for (let i = 0; i < headerConfig.length; i++) {
      //     for (let j = 0; j < datas.length; j++) {
      //       datas[j].consultTotal = (datas[j].pc || 0) + (datas[j].sdk || 0) + (datas[j].weixin || 0) + (datas[j].wxmini || 0) + (datas[j].wap || 0) + (datas[j].weibo || 0) + (datas[j].wxwork || 0) + (datas[j].ocpc || 0)
      //       if (!isNaN(datas[j][headerConfig[i].name])) {
      //         if ((headerConfig[i].name in total) === false) {
      //           total[headerConfig[i].name] = 0
      //         }
      //         total[headerConfig[i].name] += datas[j][headerConfig[i].name]
      //       }
      //     }
      //   }
      //
      //   return [total]
      // },
      // // 处理表格数据
      // getTableData (serverData) {
      //   if (!serverData || serverData.length === 0) {
      //     return []
      //   }
      //   let data = deepClone(serverData)
      //   data.forEach(item => {
      //     item.consultType = this.finishOptions[item.consultType] || this.$t('report.imReportBusinessAnalyseDeletedType')
      //     item.consultTotal = (item.pc || 0) + (item.sdk || 0) + (item.weixin || 0) + (item.wxmini || 0) + (item.wap || 0) + (item.weibo || 0) + (item.wxwork || 0) + (item.ocpc || 0)
      //   })
      //   data = sortBy(data, (item) => {
      //     return -item.consultTotal
      //   })
      //   return data
      // },
      // 展开收起方法
      isShowFold (bool) {
        this.isFold = bool
      },
      // 获取查询条件
      getSearchQueryData () {
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: { reportType: this.id }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other_half_hour') {
          // 校验类型与时间
          let message = checkTime(query.StartTime, query.EndTime, false, false)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        if (this.selectedAccessIdList.length > 0) {
          query.selectedAccessIdList = this.selectedAccessIdList.join(',')
        }
        data.query = Object.assign({}, data.query, query)
        if (this.data_type === 'allData') {
          data.completion = 'yes'
        }
        return data
      },
      search () {
        var queryData = this.getSearchQueryData()

        if (!queryData) {
          return
        }
        var query = queryData.query
        this.loading = true
        this.$store.dispatch('queryImBusinessAnalyseReport', queryData).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          //  图表标题 加入 定时段的 时间
          let highchartsTitle = ''
          if (query.timePeriod) {
            let timePeriodStartStr = query.timePeriodStart || '00:00'
            let timePeriodEndStr = query.timePeriodEnd || '23:59'
            highchartsTitle = '(' + timePeriodStartStr + '~' + timePeriodEndStr + ')'
          }
          this.highchartsDefaultOptions.title.text = this.$t('report.imReportBusinessAnalyse') + highchartsTitle
          // 表头
          this.headOptions = deepClone(res.tableHeader) || this.headOptions
          if (this.headOptions.Config && this.headOptions.Config.length > 0) {
            this.headOptions.Config.push({
              order: '99',
              name: 'consultTotal',
              displayname: this.$t('report.total2'),
              show: true
            })
          }
          this.serverData = deepClone(res.data) || this.serverData
          this.handleFetchData()
          this.loading = false
        })
      },
      exportXlsx () {
        var queryData = this.getSearchQueryData()

        if (!queryData) {
          return
        }
        // var query = queryData.query
        this.loading = true
        this.$store.dispatch('queryImBusinessAnalyseReport', queryData).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.loading = false
          var headOptions = deepClone(res.tableHeader)
          if (headOptions.Config && headOptions.Config.length > 0) {
            headOptions.Config.push({
              order: '99',
              name: 'consultTotal',
              displayname: this.$t('report.total2'),
              show: true
            })
          }
          var serverData = deepClone(res.data)
          var sum = []
          if (serverData.length !== 0) {
            // sum = this.getTotalData(serverData, headOptions)
            sum = this.totalData
          }
          // var tableData = this.getTableData(serverData, 'export').concat(sum)
          var tableData = deepClone(this.tableData).concat(sum)
          let finishLevelNum = 1 // 定义层级
          // 判断共有多少层级
          for (let i = 0; i < tableData.length; i++) {
            let item = tableData[i]
            let consultTypeArr = item.consultType.split('-->')
            let currentLevel = consultTypeArr.length
            item['consultType'] = consultTypeArr[0]
            for (let j = 1; j < currentLevel; j++) {
              item['consultType' + j] = consultTypeArr[j]
            }
            finishLevelNum = currentLevel > finishLevelNum ? currentLevel : finishLevelNum
          }
          let regArr = ['一', '二', '三', '四', '五'] // 和导出层级匹配
          // 导出分级展示
          if (headOptions.Config && headOptions.Config.length > 0) {
            for (let k = 1; k < finishLevelNum; k++) {
              headOptions.Config.splice(k, 0, {
                order: '0' + k,
                name: 'consultType' + k,
                displayname: this.$t('report.imReportconsultTypeLevel', {num: regArr[k]}),
                show: true
              })
            }
            headOptions.Config[0].displayname = this.$t('report.imReportconsultTypeLevel', {num: regArr[0]})
          }
          var headers = headOptionsToXlsxHeaders(headOptions.Config)

          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.imReportBusinessAnalyse') + timeStamp)
        })
      },
      exportXls () {
        let data = {
          Method: 'exportImBusiness',
          Query: { reportType: this.id, user: this.$store.state.session.user._id }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other_half_hour') {
          let message = checkTime(query.StartTime, query.EndTime, true, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        if (this.selectedAccessIdList.length > 0) {
          query.selectedAccessIdList = this.selectedAccessIdList.join(',')
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportImBusinessAnalyseReport', data)
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdfNew({title: this.$t('report.webchat') + this.$t('report.imReportBusinessAnalyse') + searchTime(this.query), id: this.id, tableData: this.tableData, totalData: this.totalData, headConfig: this.headOptions.Config})
      }
    },
    beforeMount () {
      let type = this.isEcommerce ? 'ecommerceAccessId' : 'accessIds'
      this.$store.dispatch('getCache', { type: type }).then(accessIds => {
        this.accessIdOptions = accessIds.map(accessId => ({ label: `${accessId.name}[${accessId.platform}]`, name: accessId.name, platform: accessId.platform, value: accessId._id }))
      })
      this.$store.dispatch('getCache', {type: 'channelDic'}).then((dics) => {
        let _dics = []
        for (var i = 0; i < dics.length; i++) {
          let obj = dics[i]
          if (obj.type === 'webchat') {
            _dics = obj.options || []
            break
          }
        }
        // 结束类型id和数据类型展示
        this.finishOptions = initFinishName(_dics, {})
        this.finishOptions.add_black = this.$t('report.addBlack')
        this.finishOptions.formQuit = this.$t('webchat.formQuit')
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .analyse
    .accs
      margin 14px 0 0px 0px
      .access
        margin-right 10px
      .el-select
        width 600px
</style>
